package com.servlet;

import com.daofactory.DaoFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 徐洲
 * @version 1.0
 */
public class AdminServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        if ("login".equals(action)){
            String enteredCaptcha = request.getParameter("captcha");
            String storedCaptcha = (String) session.getAttribute("captcha");
            //验证码
            if (enteredCaptcha != null && enteredCaptcha.equals(storedCaptcha)) {
                String admin_name = request.getParameter("admin_name");
                String admin_password = request.getParameter("admin_password");
                int admin_id = DaoFactory.getAdminDAOInstance().adminLogin(admin_name, admin_password);
                if (admin_id > 0) {
                    // 登录成功
                    session.setAttribute("admin_id", admin_id);
                    session.setAttribute("admin_name", admin_name);
                    response.sendRedirect("./admin_index.jsp");
                } else {
                    // 登录失败
                    request.setAttribute("fail","登录失败！");
                    request.getRequestDispatcher("./admin_login.jsp").forward(request, response);
                }
            }else {
                request.setAttribute("codefail","验证码错误，请重新输入");
                request.getRequestDispatcher("./admin_login.jsp").forward(request,response);
            }
        }else if ("delete".equals(action)){
            String user_id = request.getParameter("user_id");
            if (DaoFactory.getAdminDAOInstance().deleteUser(user_id)){

            }else {

            }
            response.sendRedirect("./admin_userList.jsp");
        }
//        response.sendRedirect("./infoPage.jsp");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
